//
//  ThemeViewController.swift
//  WanAndroidLearn
//
//  Created by TRS-Mobile on 2023/11/2.
//

import Foundation
import UIKit
import SwifterSwift
import ReactorKit
import RxSwift
import RxCocoa
import RxViewController

class ThemeViewController: TableViewController, View {
    typealias Reactor = ThemeVCReactor
    
    let themeReactor = ThemeVCReactor()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.reactor = ThemeVCReactor()
    }
    
    override func makeUI() {
        super.makeUI()
        title = "主题"
        tableView.register(cellWithClass: ThemeCell.self)
        tableView.rowHeight = UITableView.automaticDimension
        tableView.headRefreshControl = nil
        tableView.footRefreshControl = nil
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func bind(reactor: ThemeVCReactor) {
        
        rx.viewWillAppear
            .map { _ in ThemeVCReactor.Action.refresh }
            .bind(to: reactor.action)
            .disposed(by: disposeBag)
        
        tableView.rx
            .modelSelected(ThemeCellReactor.self)
            .map { ThemeVCReactor.Action.selection(theme: $0) }
            .bind(to: reactor.action)
            .disposed(by: disposeBag)
        
        reactor.state
            .map { $0.items }
            .asDriver(onErrorJustReturn: [])
            .drive(tableView.rx
                .items(cellIdentifier: "ThemeCell",
                       cellType: ThemeCell.self)) { idx, cellReactor, cell in
                cell.bind(reactor: cellReactor)
            }
                       .disposed(by: disposeBag)
    }
}
